package cn.cold.face;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CheckFace {
	private static final Logger log = LoggerFactory.getLogger(CheckFace.class);
	private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	private Config config;

	public void Start() {
		if (this.config.getTaskType().intValue() == 1) {
			che();
		} else if (this.config.getTaskType().intValue() == 2) {
			log.info("开始进行照片处理，仅处理两个文件夹中符合规则的照片。");
			check();
		} else {
			log.error("没有此任务类型");
		}
	}

	public void che() {
		LinkedList<File> idnames = traverseFolder1(this.config.getIdPath());
		if (idnames.size() <= 0) {
			log.error("对不起第一个相册没有查找到照片,程序结束");
			return;
		}
		LinkedList<File> peoplenames = traverseFolder1(this.config.getPeoplePath());
		if (peoplenames.size() <= 0) {
			log.error("对不起第二个相册没有查找到照片,程序结束");
			return;
		}
		log.info("开始进行照片处理，仅处理两个文件夹中符合规则的照片。");
		for (int i = 0; i < idnames.size(); i++) {
			String idname = "";
			try {
				idname = ((File) idnames.get(i)).getName().trim().substring(0,
						((File) idnames.get(i)).getName().indexOf("-"));
			} catch (StringIndexOutOfBoundsException e) {
				e.printStackTrace();
				log.error("截取错误");
				continue;
			} catch (Exception e) {
				e.printStackTrace();
				log.error("未知错误");
				continue;
			}
			if ((idname == "") || (idname == null)) {
				log.error("null");
			} else {
				for (int j = 0; j < peoplenames.size(); j++) {
					String people = "";
					try {
						people = ((File) peoplenames.get(j)).getName().trim().substring(0,
								((File) peoplenames.get(j)).getName().indexOf("-"));
					} catch (StringIndexOutOfBoundsException e) {
						e.printStackTrace();
						log.error("截取错误");
						continue;
					} catch (Exception e) {
						e.printStackTrace();
						log.error("未知错误");
						continue;
					}
					if ((people == "") || (people == null)) {
						log.error("null");
						break;
					}
					if (idname.equals(people)) {
						long start = System.currentTimeMillis();
						log.info("开始比对：{},{},开始时间：{}", new Object[] { ((File) idnames.get(i)).getName(),
								((File) peoplenames.get(j)).getName(), SDF.format(Long.valueOf(start)) });

						SimpleIDSearchResponse response = null;
						try {
							response = MinshApi.OneToOne(((File) idnames.get(i)).getAbsolutePath(),
									((File) peoplenames.get(j)).getAbsolutePath(), config.getAddress());
						} catch (Exception e) {
							e.printStackTrace();
						}
						log.info("结束比对：{},{},结束时间：{}",
								new Object[] { ((File) idnames.get(i)).getName(), ((File) peoplenames.get(j)).getName(),
										SDF.format(Long.valueOf(System.currentTimeMillis())) });
						method1(((File) idnames.get(i)).getName() + "," + ((File) peoplenames.get(j)).getName() + ","
								+ response.getPairVerifySimilarity() + ","
								+ (response.getPairVerifyResult() == 0 ? "YES" : "NO"), this.config.getSavePath());
					}
				}
			}
		}
		log.info("所有比对结束,程序结束");
	}

	public void check() {
		long start = System.currentTimeMillis();
		long times = this.config.getTime().intValue() * 60000;
		int runTaskNumber = this.config.getRunTaskNumber().intValue();
		int loopCount = 0;
		TaskState task = new TaskState();
		while (System.currentTimeMillis() - start <= times) {
			checkFace(runTaskNumber, task);
			loopCount++;
			while (System.currentTimeMillis() - start < loopCount * 1000) {
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		while (task.getTaskCount().intValue() > 0) {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		method1("平均请求时间为：" + task.Avg(), this.config.getSavePath());
		method1("最大时间为：" + task.getMaxTime(), this.config.getSavePath());
		method1("最小时间为：" + task.getMixTime(), this.config.getSavePath());
		method1("总请求时间：" + task.Sum(), this.config.getSavePath());
		method1("总请求数：" + task.getTime().size(), this.config.getSavePath());
		method1("超时数：" + task.getTimeoutCount(), this.config.getSavePath());
		method1("总请求数：" + task.getErrorCount(), this.config.getSavePath());
	}

	private void checkFace(int count, TaskState sk) {
		int number = 0;
		for (int i = 0; i < count; i++) {
			CallFaceTask task = new CallFaceTask(this.config.getIdPath(), this.config.getPeoplePath(),
					this.config.getSavePath(), Integer.valueOf(number));
			task.setAddress(config.getAddress());
			task.setTask(sk);
			task.setI(number);
			Thread th = new Thread(task);
			th.start();
			number++;
		}
	}

	public static LinkedList<File> traverseFolder1(String path) {
		LinkedList<File> list = null;
		File file = new File(path);
		if (file.exists()) {
			list = new LinkedList<File>();
			File[] files = file.listFiles();
			for (File file2 : files) {
				if (file2.isDirectory()) {
					System.out.println("文件夹:" + file2.getAbsolutePath());
				} else {
					list.add(file2);
				}
			}
		}
		return list;
	}

	public static void method1(String context, String path) {
		FileWriter fw = null;
		try {
			if ((!path.substring(path.length() - 1, path.length()).equals("/"))
					|| (!path.substring(path.length() - 1, path.length()).equals("\\"))) {
				path = path + "/";
			}
			File f = new File(path);
			if (!f.exists()) {
				f.mkdirs();
			}
			f = new File(path + "result.csv");
			fw = new FileWriter(f, true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		pw.println(context);
		pw.flush();
		try {
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
